<?php
namespace interface\v1;
/*
*来访登记接口类
*/

use verify;

class visitAppClass extends index
{
    private const page = 'visitor';
    private const table = 'visitor';
    private const title = '来访登记';
    /*选项*/
    public function search()
    {
        $this->code = 1;
        $data['result'] = [
            'idOption' => explode('，', para('visitorCertType')),
            'carNoOption' => explode('，', para('shortNameOption'))
        ];
        $this->resp['data'] = $data;
    }

    /**
     * 编辑
     */
    public function commitEdit(){
        $id = $this->post('id') ?: self::getId();
        $field = [
            'shortName' => $this->post('shortName'),
            'carNo' => $this->post('carNo'),
            'name' => $this->post('name'),
            'contactTel' => $this->post('contactTel'),
            'type' => $this->post('type'),
            'idNum' => $this->post('idNum'),
            'leaveTime' => $this->post('leaveTime'),
            'reason' => $this->post('reason'),
            'managerId' =>'',
        ];
        $field['visitDate'] = date('Y-m-d',strtotime($this->post('arrivalTime')));
        $field['arrivalTime'] = date('H:i:s',strtotime($this->post('arrivalTime')));
        $annotation = [
            'visitDate' => '日期',
            'name' => '姓名',
            'contactTel' => '联系方式',
            'arrivalTime' => '来访时间',
            'reason' => '来访事由',
        ];
        $rules = [
            'visitDate' => 'required',
            'name' => 'required',
            'contactTel' => 'required',
            'arrivalTime' => 'required',
            'reason' => 'required',
        ];
        // 校验是否符合规则
        $vt = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if(empty($this->post('arrivalTime'))){
            $this->resp['warn'] = '请选择来访时间';
        } elseif(self::total(array('table'=>self::table,'where'=>"contactTel ='$field[contactTel]' and visitDate = '".$this->date."'")) ==3){
            $this->resp['warn'] = '最多提交3条申请';
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = self::generateCode(self::page,[
                    'prefix' => 'LFDJ',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
//                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
//                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
//                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
//                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $this->code = 1;
            }
            $this->resp['warn'] = $json['warn'];
        }
        resp:
    }

    /**
     * 编辑
     */
    public function appCommitEdit(){
        $id = self::getId();
        $field = [
            'role_type1' => $this->post('role_type1'),
            'role_type2' => $this->post('role_type2'),
            'role_type2_1' => $this->post('role_type2_1'),
            'approach' => $this->post('approach'),
            'leaving' => $this->post('leaving'),
            'idNum' => $this->post('idNum'),
            'borrowInfo' => $this->post('borrowInfo'),
            'leaveUnit' => $this->post('leaveUnit'),
            'name' => $this->post('name'),
            'contactTel' => $this->post('contactTel'),
            'shortName' => $this->post('shortName'),
            'carNo' => $this->post('carNo'),
            'arrivalTime' => $this->post('arrivalTime'),
            'leaveTime' => $this->post('leaveTime'),
            'visitDate' => $this->post('visitDate'),
            'managerId' => $this->post('managerId'),
            'reason' => $this->post('reason'),
            'type' => $this->post('type'),
            'updateTime' => $this->time
        ];
        $annotation = [
//            'visitDate' => '日期',
            'name' => '姓名',
            'type' => '类型',
            'role_type1' => '提货角色',
            'contactTel' => '联系方式',
            'arrivalTime' => '来访时间',
            'reason' => '来访事由',
            'idNum' => '证件号码',
        ];
        $rules = [
//            'visitDate' => 'required',
            'type' => 'required',
            'role_type1' => 'required',
            'name' => 'required',
            'contactTel' => 'required',
            'arrivalTime' => 'required',
            'reason' => 'required',
            'idNum' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->code = 2;
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if(!self::isValidChineseId($field['idNum'])){
            $this->code = 2;
            $json['warn'] = "请正确输入证件号码";  // 多个规则提示最前面一条
            goto resp;
        }
        $safety_registration = query('safety_registration',"idNum = '$field[idNum]'");
        if(empty($safety_registration['id'])){
            $this->code = 2;
            $json['warn'] = "请先进行安全告知登记";  // 多个规则提示最前面一条
            goto resp;
        }
        if($safety_registration['endVisitDate'] < date("Y-m-d")){
            $this->code = 2;
            $json['warn'] = "安全告知登记已过期";  // 多个规则提示最前面一条
            goto resp;
        }

        $field = array_merge($field, [
            'id' => $id,
//            'stid' => $this->control['stid'],
            'time' => $this->time
        ]);
        $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
        if(!empty($_FILES['file'])){
            //上传附件
            $this->addFile($id);
        }
        $this->code = 1;
        resp:
        $this->resp['warn'] = $json['warn'];
    }

    public function addFile($targetId)
    {
        $id = self::getId();
        $fileName = "file";//附件上传域名称
        $tmp_name = $_FILES[$fileName]['tmp_name'];//临时文件名
        $name = $_FILES[$fileName]['name'];    //附件名称
        $nameArr = explode('.', $name);
        $suffix = end($nameArr);//附件后缀
        $filesize = filesize($tmp_name);
        if (!in_array($suffix, explode(",", para("fileFormat")))) {
            $warn = "文件后缀【" . $suffix . "】不在白名单中";
        } elseif (sqlNum("file", " targetId = '" . $targetId . "' and name = '$name' ") > 0) {
            $warn = "此附件已存在";
        } else {
            $url = "file/attachment/" . date("Ym");
            if (!file_exists(serverRoot . $url)) {
                self::_mkdir($url);
            }
            $src = $url . "/" . $id . "." . $suffix;//保存附件的根目录路径
            $warn = insert(array(
                "table" => "file",
                "field" => array(
                    "id" => $id,
                    "stid" => $this->control['stid'],
                    "target" => '来访登记',//目标对象
                    "targetId" => $targetId,//上传对象ID号
                    "name" => $name,
                    "secret" => "否",
                    "format" => $suffix,
                    "size" => $filesize,
                    "src" => $src,
                    "time" => date("Y-m-d H:i:s"),
                ),
            ));
            if ($warn == "新增成功") {
                move_uploaded_file($tmp_name, serverRoot . $src);
                return true;
            }
        }
        return $warn;
    }

    public function leaveEdit()
    {
        $idNum = $this->post('idNum');
        $info = query(self::table,"idNum='{$idNum}'");
        if(!$info){
            $this->code = 2;
            $json['warn'] = "未找到用户的入场记录";
        }else{
            $this->code = 1;
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => ['leaveTime'=>$this->time,'isBorrowInfo' => $this->post('borrowInfo'),'endApproach' => $this->post('approach'),],
                "where" => " id = '{$info['id']}' "
            ]);
        }
        $this->resp['warn'] = $json['warn'];
    }

    public static function isValidChineseId($id) {
        if (strlen($id) != 18) {
            return false;
        }
        $weights = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        $checkcodes = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            $sum += $weights[$i] * intval(substr($id, $i, 1));
        }
        $mod = $sum % 11;
        $checkcode = $checkcodes[$mod];
        return $checkcode == strtoupper(substr($id, 17, 1));
    }
}